<template>
  <div class="member-management-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>会员管理</h2>
      <p>管理会员信息、等级、积分和优惠券等</p>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon">
              <el-icon size="32" color="#409EFF"><User /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ memberStats.totalMembers }}</div>
              <div class="stats-label">总会员数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon">
              <el-icon size="32" color="#67C23A"><Star /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ memberStats.activeMembers }}</div>
              <div class="stats-label">活跃会员</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon">
              <el-icon size="32" color="#E6A23C"><Coin /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ memberStats.totalPoints }}</div>
              <div class="stats-label">总积分</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon">
              <el-icon size="32" color="#F56C6C"><Ticket /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ memberStats.activeCoupons }}</div>
              <div class="stats-label">有效优惠券</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搜索和筛选区域 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="会员姓名">
          <el-input v-model="searchForm.memberName" placeholder="请输入会员姓名" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="searchForm.phone" placeholder="请输入手机号" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="会员等级">
          <el-select v-model="searchForm.level" placeholder="请选择等级" clearable style="width: 150px">
            <el-option label="普通会员" value="bronze" />
            <el-option label="银卡会员" value="silver" />
            <el-option label="金卡会员" value="gold" />
            <el-option label="钻石会员" value="diamond" />
            <el-option label="黑卡会员" value="black" />
          </el-select>
        </el-form-item>
        <el-form-item label="会员状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 150px">
            <el-option label="正常" value="active" />
            <el-option label="冻结" value="frozen" />
            <el-option label="注销" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="注册时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card class="action-card" shadow="never">
      <div class="action-buttons">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增会员
        </el-button>
        <el-button type="success" @click="handleBatchPoints">
          <el-icon><Coin /></el-icon>
          批量积分
        </el-button>
        <el-button type="warning" @click="handleBatchCoupon">
          <el-icon><Ticket /></el-icon>
          批量发券
        </el-button>
        <el-button type="info" @click="handleExport">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <el-table
        :data="tableData"
        v-loading="loading"
        stripe
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="memberNo" label="会员编号" width="120" fixed="left" />
        <el-table-column prop="avatar" label="头像" width="80">
          <template #default="{ row }">
            <el-avatar :src="row.avatar" :size="40">
              <el-icon><User /></el-icon>
            </el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="memberName" label="会员姓名" width="120" />
        <el-table-column prop="phone" label="手机号" width="130" />
        <el-table-column prop="gender" label="性别" width="80">
          <template #default="{ row }">
            <el-tag :type="row.gender === '男' ? 'primary' : 'danger'" size="small">
              {{ row.gender }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="level" label="会员等级" width="120">
          <template #default="{ row }">
            <el-tag :type="getLevelTagType(row.level)" :color="getLevelColor(row.level)">
              {{ getLevelText(row.level) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="points" label="积分余额" width="100">
          <template #default="{ row }">
            <span class="points-text">{{ row.points }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="totalConsumption" label="累计消费" width="120">
          <template #default="{ row }">
            <span class="amount-text">¥{{ row.totalConsumption.toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="lastVisit" label="最后访问" width="160" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="registerTime" label="注册时间" width="160" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">
              查看
            </el-button>
            <el-button type="success" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-dropdown @command="(command) => handleDropdownCommand(command, row)">
              <el-button type="info" size="small">
                更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="points">积分操作</el-dropdown-item>
                  <el-dropdown-item command="coupon">发放优惠券</el-dropdown-item>
                  <el-dropdown-item command="upgrade">等级调整</el-dropdown-item>
                  <el-dropdown-item command="freeze" v-if="row.status === 'active'">冻结账户</el-dropdown-item>
                  <el-dropdown-item command="unfreeze" v-if="row.status === 'frozen'">解冻账户</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 会员详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="会员详情" width="70%" :before-close="handleDetailClose">
      <div v-if="currentMember" class="member-detail">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="基本信息" name="basic">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="会员编号">{{ currentMember.memberNo }}</el-descriptions-item>
              <el-descriptions-item label="会员姓名">{{ currentMember.memberName }}</el-descriptions-item>
              <el-descriptions-item label="手机号">{{ currentMember.phone }}</el-descriptions-item>
              <el-descriptions-item label="性别">{{ currentMember.gender }}</el-descriptions-item>
              <el-descriptions-item label="生日">{{ currentMember.birthday }}</el-descriptions-item>
              <el-descriptions-item label="邮箱">{{ currentMember.email }}</el-descriptions-item>
              <el-descriptions-item label="会员等级">
                <el-tag :type="getLevelTagType(currentMember.level)" :color="getLevelColor(currentMember.level)">
                  {{ getLevelText(currentMember.level) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="状态">
                <el-tag :type="getStatusTagType(currentMember.status)">
                  {{ getStatusText(currentMember.status) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="注册时间">{{ currentMember.registerTime }}</el-descriptions-item>
              <el-descriptions-item label="最后访问">{{ currentMember.lastVisit }}</el-descriptions-item>
              <el-descriptions-item label="地址" :span="2">{{ currentMember.address }}</el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>
          
          <el-tab-pane label="积分记录" name="points">
            <el-table :data="currentMember.pointsHistory" border>
              <el-table-column prop="date" label="日期" width="160" />
              <el-table-column prop="type" label="类型" width="100">
                <template #default="{ row }">
                  <el-tag :type="row.type === '获得' ? 'success' : 'warning'" size="small">
                    {{ row.type }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="points" label="积分变动" width="100">
                <template #default="{ row }">
                  <span :class="row.type === '获得' ? 'points-gain' : 'points-cost'">
                    {{ row.type === '获得' ? '+' : '-' }}{{ row.points }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column prop="balance" label="余额" width="100" />
              <el-table-column prop="reason" label="原因" />
            </el-table>
          </el-tab-pane>
          
          <el-tab-pane label="优惠券" name="coupons">
            <el-table :data="currentMember.coupons" border>
              <el-table-column prop="name" label="优惠券名称" />
              <el-table-column prop="type" label="类型" width="100">
                <template #default="{ row }">
                  <el-tag :type="getCouponTypeTag(row.type)" size="small">
                    {{ getCouponTypeText(row.type) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="value" label="面额/折扣" width="120">
                <template #default="{ row }">
                  {{ row.type === 'discount' ? row.value + '折' : '¥' + row.value }}
                </template>
              </el-table-column>
              <el-table-column prop="minAmount" label="最低消费" width="100">
                <template #default="{ row }">
                  ¥{{ row.minAmount }}
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" width="80">
                <template #default="{ row }">
                  <el-tag :type="getCouponStatusTag(row.status)" size="small">
                    {{ getCouponStatusText(row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="expireTime" label="过期时间" width="160" />
            </el-table>
          </el-tab-pane>
          
          <el-tab-pane label="消费记录" name="consumption">
            <el-table :data="currentMember.consumptionHistory" border>
              <el-table-column prop="date" label="消费日期" width="160" />
              <el-table-column prop="orderNo" label="订单号" width="180" />
              <el-table-column prop="amount" label="消费金额" width="120">
                <template #default="{ row }">
                  <span class="amount-text">¥{{ row.amount.toFixed(2) }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="pointsEarned" label="获得积分" width="100" />
              <el-table-column prop="channel" label="消费渠道" width="120" />
              <el-table-column prop="products" label="商品" show-overflow-tooltip />
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>

    <!-- 新增/编辑会员对话框 -->
    <el-dialog v-model="formDialogVisible" :title="isEdit ? '编辑会员' : '新增会员'" width="50%">
      <el-form :model="memberForm" :rules="memberRules" ref="memberFormRef" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="会员姓名" prop="memberName">
              <el-input v-model="memberForm.memberName" placeholder="请输入会员姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="memberForm.phone" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="memberForm.gender">
                <el-radio label="男">男</el-radio>
                <el-radio label="女">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生日">
              <el-date-picker
                v-model="memberForm.birthday"
                type="date"
                placeholder="请选择生日"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="邮箱">
              <el-input v-model="memberForm.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="会员等级">
              <el-select v-model="memberForm.level" placeholder="请选择等级" style="width: 100%">
                <el-option label="普通会员" value="bronze" />
                <el-option label="银卡会员" value="silver" />
                <el-option label="金卡会员" value="gold" />
                <el-option label="钻石会员" value="diamond" />
                <el-option label="黑卡会员" value="black" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="地址">
          <el-input v-model="memberForm.address" type="textarea" :rows="2" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="memberForm.remark" type="textarea" :rows="2" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="formDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 积分操作对话框 -->
    <el-dialog v-model="pointsDialogVisible" title="积分操作" width="40%">
      <el-form :model="pointsForm" :rules="pointsRules" ref="pointsFormRef" label-width="100px">
        <el-form-item label="操作类型" prop="type">
          <el-radio-group v-model="pointsForm.type">
            <el-radio label="add">增加积分</el-radio>
            <el-radio label="deduct">扣减积分</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="积分数量" prop="points">
          <el-input-number v-model="pointsForm.points" :min="1" :max="99999" style="width: 100%" />
        </el-form-item>
        <el-form-item label="操作原因" prop="reason">
          <el-input v-model="pointsForm.reason" type="textarea" :rows="3" placeholder="请输入操作原因" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="pointsDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handlePointsSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Download, User, Star, Coin, Ticket, ArrowDown } from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const detailDialogVisible = ref(false)
const formDialogVisible = ref(false)
const pointsDialogVisible = ref(false)
const isEdit = ref(false)
const currentMember = ref(null)
const selectedMembers = ref([])
const activeTab = ref('basic')
const memberFormRef = ref(null)
const pointsFormRef = ref(null)

// 会员统计数据
const memberStats = reactive({
  totalMembers: 15680,
  activeMembers: 12450,
  totalPoints: 2580000,
  activeCoupons: 8960
})

// 搜索表单
const searchForm = reactive({
  memberName: '',
  phone: '',
  level: '',
  status: '',
  dateRange: []
})

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 会员表单
const memberForm = reactive({
  memberName: '',
  phone: '',
  gender: '男',
  birthday: '',
  email: '',
  level: 'bronze',
  address: '',
  remark: ''
})

// 积分操作表单
const pointsForm = reactive({
  type: 'add',
  points: 0,
  reason: ''
})

// 表单验证规则
const memberRules = {
  memberName: [{ required: true, message: '请输入会员姓名', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }]
}

const pointsRules = {
  type: [{ required: true, message: '请选择操作类型', trigger: 'change' }],
  points: [{ required: true, message: '请输入积分数量', trigger: 'blur' }],
  reason: [{ required: true, message: '请输入操作原因', trigger: 'blur' }]
}

// 模拟数据
const mockData = [
  {
    id: 1,
    memberNo: 'M202401001',
    avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
    memberName: '张三',
    phone: '13800138001',
    gender: '男',
    birthday: '1990-05-15',
    email: 'zhangsan@example.com',
    level: 'gold',
    points: 2580,
    totalConsumption: 15680.00,
    lastVisit: '2024-01-15 14:30:00',
    status: 'active',
    registerTime: '2023-03-15 10:20:00',
    address: '北京市朝阳区建国路88号SOHO现代城',
    pointsHistory: [
      { date: '2024-01-15', type: '获得', points: 158, balance: 2580, reason: '购物消费' },
      { date: '2024-01-10', type: '使用', points: 100, balance: 2422, reason: '兑换商品' },
      { date: '2024-01-05', type: '获得', points: 200, balance: 2522, reason: '生日奖励' }
    ],
    coupons: [
      { name: '满100减20优惠券', type: 'cash', value: 20, minAmount: 100, status: 'unused', expireTime: '2024-02-15' },
      { name: '8.8折优惠券', type: 'discount', value: 8.8, minAmount: 200, status: 'used', expireTime: '2024-01-31' }
    ],
    consumptionHistory: [
      { date: '2024-01-15', orderNo: 'RT202401150001', amount: 299.00, pointsEarned: 29, channel: '线上商城', products: 'iPhone手机壳, 数据线' },
      { date: '2024-01-10', orderNo: 'RT202401100005', amount: 158.00, pointsEarned: 15, channel: '门店', products: '蓝牙耳机' }
    ]
  },
  {
    id: 2,
    memberNo: 'M202401002',
    avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
    memberName: '李四',
    phone: '13800138002',
    gender: '女',
    birthday: '1985-08-20',
    email: 'lisi@example.com',
    level: 'diamond',
    points: 5680,
    totalConsumption: 28900.00,
    lastVisit: '2024-01-14 16:45:00',
    status: 'active',
    registerTime: '2022-11-08 09:15:00',
    address: '上海市浦东新区陆家嘴环路1000号',
    pointsHistory: [
      { date: '2024-01-14', type: '获得', points: 289, balance: 5680, reason: '购物消费' },
      { date: '2024-01-12', type: '获得', points: 500, balance: 5391, reason: '等级升级奖励' }
    ],
    coupons: [
      { name: '满500减100优惠券', type: 'cash', value: 100, minAmount: 500, status: 'unused', expireTime: '2024-03-15' },
      { name: '9折优惠券', type: 'discount', value: 9, minAmount: 300, status: 'unused', expireTime: '2024-02-28' }
    ],
    consumptionHistory: [
      { date: '2024-01-14', orderNo: 'RT202401140003', amount: 1299.00, pointsEarned: 129, channel: 'APP', products: '笔记本电脑' },
      { date: '2024-01-08', orderNo: 'RT202401080012', amount: 599.00, pointsEarned: 59, channel: '微信小程序', products: '智能手表' }
    ]
  },
  {
    id: 3,
    memberNo: 'M202401003',
    avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
    memberName: '王五',
    phone: '13800138003',
    gender: '男',
    birthday: '1992-12-10',
    email: 'wangwu@example.com',
    level: 'silver',
    points: 1250,
    totalConsumption: 5680.00,
    lastVisit: '2024-01-13 11:20:00',
    status: 'active',
    registerTime: '2023-08-22 14:30:00',
    address: '广州市天河区珠江新城花城大道123号',
    pointsHistory: [
      { date: '2024-01-13', type: '获得', points: 89, balance: 1250, reason: '购物消费' },
      { date: '2024-01-08', type: '使用', points: 200, balance: 1161, reason: '兑换优惠券' }
    ],
    coupons: [
      { name: '满200减30优惠券', type: 'cash', value: 30, minAmount: 200, status: 'unused', expireTime: '2024-02-20' }
    ],
    consumptionHistory: [
      { date: '2024-01-13', orderNo: 'RT202401130008', amount: 89.90, pointsEarned: 8, channel: '线上商城', products: '智能手环' }
    ]
  },
  {
    id: 4,
    memberNo: 'M202401004',
    avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
    memberName: '赵六',
    phone: '13800138004',
    gender: '女',
    birthday: '1988-03-25',
    email: 'zhaoliu@example.com',
    level: 'bronze',
    points: 680,
    totalConsumption: 2350.00,
    lastVisit: '2024-01-12 09:15:00',
    status: 'frozen',
    registerTime: '2023-12-05 16:45:00',
    address: '深圳市南山区科技园南区深南大道9999号',
    pointsHistory: [
      { date: '2024-01-12', type: '获得', points: 45, balance: 680, reason: '购物消费' }
    ],
    coupons: [],
    consumptionHistory: [
      { date: '2024-01-12', orderNo: 'RT202401120015', amount: 45.80, pointsEarned: 4, channel: '门店', products: '保温杯' }
    ]
  },
  {
    id: 5,
    memberNo: 'M202401005',
    avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
    memberName: '孙七',
    phone: '13800138005',
    gender: '男',
    birthday: '1995-07-18',
    email: 'sunqi@example.com',
    level: 'black',
    points: 12580,
    totalConsumption: 58900.00,
    lastVisit: '2024-01-15 18:20:00',
    status: 'active',
    registerTime: '2021-05-10 11:30:00',
    address: '杭州市西湖区文三路508号天苑大厦',
    pointsHistory: [
      { date: '2024-01-15', type: '获得', points: 589, balance: 12580, reason: '购物消费' },
      { date: '2024-01-10', type: '获得', points: 1000, balance: 11991, reason: 'VIP专享奖励' }
    ],
    coupons: [
      { name: '满1000减200优惠券', type: 'cash', value: 200, minAmount: 1000, status: 'unused', expireTime: '2024-04-15' },
      { name: '8折优惠券', type: 'discount', value: 8, minAmount: 500, status: 'unused', expireTime: '2024-03-31' },
      { name: '免邮券', type: 'shipping', value: 0, minAmount: 0, status: 'unused', expireTime: '2024-02-29' }
    ],
    consumptionHistory: [
      { date: '2024-01-15', orderNo: 'RT202401150020', amount: 5899.00, pointsEarned: 589, channel: '线上商城', products: '高端数码产品套装' },
      { date: '2024-01-08', orderNo: 'RT202401080025', amount: 2999.00, pointsEarned: 299, channel: 'APP', products: '智能家居套装' }
    ]
  }
]

// 获取等级标签类型
const getLevelTagType = (level) => {
  const levelMap = {
    bronze: '',
    silver: 'info',
    gold: 'warning',
    diamond: 'success',
    black: 'danger'
  }
  return levelMap[level] || ''
}

// 获取等级颜色
const getLevelColor = (level) => {
  const colorMap = {
    bronze: '#CD7F32',
    silver: '#C0C0C0',
    gold: '#FFD700',
    diamond: '#B9F2FF',
    black: '#2C2C2C'
  }
  return colorMap[level] || '#909399'
}

// 获取等级文本
const getLevelText = (level) => {
  const levelMap = {
    bronze: '普通会员',
    silver: '银卡会员',
    gold: '金卡会员',
    diamond: '钻石会员',
    black: '黑卡会员'
  }
  return levelMap[level] || '未知'
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const statusMap = {
    active: 'success',
    frozen: 'warning',
    cancelled: 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    active: '正常',
    frozen: '冻结',
    cancelled: '注销'
  }
  return statusMap[status] || '未知'
}

// 获取优惠券类型标签
const getCouponTypeTag = (type) => {
  const typeMap = {
    cash: 'danger',
    discount: 'warning',
    shipping: 'success'
  }
  return typeMap[type] || 'info'
}

// 获取优惠券类型文本
const getCouponTypeText = (type) => {
  const typeMap = {
    cash: '满减券',
    discount: '折扣券',
    shipping: '免邮券'
  }
  return typeMap[type] || '未知'
}

// 获取优惠券状态标签
const getCouponStatusTag = (status) => {
  const statusMap = {
    unused: 'success',
    used: 'info',
    expired: 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取优惠券状态文本
const getCouponStatusText = (status) => {
  const statusMap = {
    unused: '未使用',
    used: '已使用',
    expired: '已过期'
  }
  return statusMap[status] || '未知'
}

// 搜索
const handleSearch = () => {
  loading.value = true
  setTimeout(() => {
    loadData()
    loading.value = false
  }, 500)
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    memberName: '',
    phone: '',
    level: '',
    status: '',
    dateRange: []
  })
  handleSearch()
}

// 新增会员
const handleAdd = () => {
  isEdit.value = false
  Object.assign(memberForm, {
    memberName: '',
    phone: '',
    gender: '男',
    birthday: '',
    email: '',
    level: 'bronze',
    address: '',
    remark: ''
  })
  formDialogVisible.value = true
}

// 编辑会员
const handleEdit = (row) => {
  isEdit.value = true
  Object.assign(memberForm, {
    id: row.id,
    memberName: row.memberName,
    phone: row.phone,
    gender: row.gender,
    birthday: row.birthday,
    email: row.email,
    level: row.level,
    address: row.address,
    remark: row.remark || ''
  })
  formDialogVisible.value = true
}

// 查看会员详情
const handleView = (row) => {
  currentMember.value = row
  activeTab.value = 'basic'
  detailDialogVisible.value = true
}

// 关闭详情对话框
const handleDetailClose = () => {
  detailDialogVisible.value = false
  currentMember.value = null
}

// 下拉菜单命令处理
const handleDropdownCommand = async (command, row) => {
  switch (command) {
    case 'points':
      await handlePointsOperation(row)
      break
    case 'coupon':
      await handleSendCoupon(row)
      break
    case 'upgrade':
      await handleLevelAdjust(row)
      break
    case 'freeze':
      await handleFreeze(row)
      break
    case 'unfreeze':
      await handleUnfreeze(row)
      break
  }
}

// 积分操作
const handlePointsOperation = (row) => {
  currentMember.value = row
  Object.assign(pointsForm, {
    type: 'add',
    points: 0,
    reason: ''
  })
  pointsDialogVisible.value = true
}

// 发放优惠券
const handleSendCoupon = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要为会员 ${row.memberName} 发放优惠券吗？`, '确认发放', {
      type: 'info'
    })
    ElMessage.success('优惠券发放成功')
    loadData()
  } catch {
    // 用户取消
  }
}

// 等级调整
const handleLevelAdjust = async (row) => {
  try {
    const { value } = await ElMessageBox.prompt('请选择新的会员等级', '等级调整', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputType: 'select',
      inputOptions: {
        bronze: '普通会员',
        silver: '银卡会员',
        gold: '金卡会员',
        diamond: '钻石会员',
        black: '黑卡会员'
      }
    })
    ElMessage.success('会员等级调整成功')
    loadData()
  } catch {
    // 用户取消
  }
}

// 冻结账户
const handleFreeze = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要冻结会员 ${row.memberName} 的账户吗？`, '确认冻结', {
      type: 'warning'
    })
    ElMessage.success('账户已冻结')
    loadData()
  } catch {
    // 用户取消
  }
}

// 解冻账户
const handleUnfreeze = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要解冻会员 ${row.memberName} 的账户吗？`, '确认解冻', {
      type: 'info'
    })
    ElMessage.success('账户已解冻')
    loadData()
  } catch {
    // 用户取消
  }
}

// 批量积分
const handleBatchPoints = () => {
  if (selectedMembers.value.length === 0) {
    ElMessage.warning('请选择要操作的会员')
    return
  }
  ElMessage.success('批量积分功能开发中...')
}

// 批量发券
const handleBatchCoupon = () => {
  if (selectedMembers.value.length === 0) {
    ElMessage.warning('请选择要操作的会员')
    return
  }
  ElMessage.success('批量发券功能开发中...')
}

// 导出数据
const handleExport = () => {
  ElMessage.success('导出功能开发中...')
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedMembers.value = selection
}

// 提交会员表单
const handleSubmit = async () => {
  try {
    await memberFormRef.value.validate()
    ElMessage.success(isEdit.value ? '会员信息更新成功' : '会员创建成功')
    formDialogVisible.value = false
    loadData()
  } catch {
    // 验证失败
  }
}

// 提交积分操作
const handlePointsSubmit = async () => {
  try {
    await pointsFormRef.value.validate()
    ElMessage.success('积分操作成功')
    pointsDialogVisible.value = false
    loadData()
  } catch {
    // 验证失败
  }
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  loadData()
}

// 当前页变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadData()
}

// 加载数据
const loadData = () => {
  loading.value = true
  setTimeout(() => {
    tableData.value = mockData
    pagination.total = mockData.length
    loading.value = false
  }, 300)
}

// 组件挂载时加载数据
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.member-management-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.stats-row {
  margin-bottom: 20px;
}

.stats-card {
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.stats-content {
  display: flex;
  align-items: center;
  padding: 10px;
}

.stats-icon {
  margin-right: 15px;
}

.stats-info {
  flex: 1;
}

.stats-number {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 5px;
}

.stats-label {
  font-size: 14px;
  color: #909399;
}

.search-card,
.action-card,
.table-card {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 0;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.points-text {
  color: #E6A23C;
  font-weight: 600;
}

.amount-text {
  color: #f56c6c;
  font-weight: 600;
}

.points-gain {
  color: #67C23A;
  font-weight: 600;
}

.points-cost {
  color: #F56C6C;
  font-weight: 600;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.member-detail {
  max-height: 70vh;
  overflow-y: auto;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

@media (max-width: 768px) {
  .member-management-container {
    padding: 10px;
  }
  
  .stats-row {
    flex-direction: column;
  }
  
  .search-form {
    flex-direction: column;
  }
  
  .action-buttons {
    flex-direction: column;
  }
}
</style>